<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>OpenLayers Test</title>
    <link rel="stylesheet" href="custom/libs/OpenLayers/ol.css" type="text/css">

    <script type="text/javascript">
        htconfig = {
            Default: {
                paletteTitleBackground: 'rgb(240,239,238)',
                paletteTitleHoverBackground: 'rgb(231,231,231)',
                paletteTitleLabelColor: 'rgb(138, 138, 138)',
                paletteItemSelectBackground: '',
                paletteItemHoverBorderColor: 'rgb(138, 138, 138)',

                toolTipBackground: 'rgb(255, 255, 255)',

                dialogButtonBackground: 'rgb(231, 76, 60)',
                dialogButtonSelectBackground: 'rgb(196, 65, 51)',
                dialogButtonLabelColor: '#fff',

                buttonBackground: '',
                buttonSelectBackground: 'rgb(231, 231, 231)',
                buttonLabelColor: 'rgb(159, 159, 159)',
                comboBoxLabelColor: 'rgb(159, 159, 159)',
                comboBoxSelectBackground: 'rgb(138, 138, 138)'
            },
            Color: {
                titleBackground: '#076186',// 指定HT所有组件的标题栏的背景色，如面板，对话框，AccordionView等
                titleIconBackground: 'rgb(186, 186, 186)',// 指定HT所有组件的标题ICON的颜色，如面板，对话框，AccordionView等
                headerBackground: '#DAECF4'// 指定HT所有组件的header背景色，如表格表头、工具条等
            }
        };
    </script>
    <script src="../libs/core/ht.js"></script>
    <script src="../libs/core/ht-ui.js"></script>
    <script src="../libs/plugin/ht-cssanimation.js"></script>
    <script src="../libs/plugin/ht-palette.js"></script>
    <script src="../libs/plugin/ht-form.js"></script>
    <script src="../libs/plugin/ht-dialog.js"></script>
    <script src="../libs/plugin/ht-edgetype.js"></script>

    <script src="custom/libs/OpenLayers/ol-debug.js"></script>
    <!-- <script src="custom/libs/OpenLayers/CreateEdgeInteractor.js"></script>
	<script src="custom/libs/OpenLayers/CreateShapeInteractor.js"></script> -->
    <script src="custom/libs/OpenLayers/GraphViewControl.js"></script>

    <style type="text/css">
        html,
        body {
            margin: 0;
            padding: 0;
        }
    </style>

    <script type="text/javascript">
        graphViewControl = new GraphViewControl();// 自定义控件，作为 openlayers 地图上自定义控件
        graphView = graphViewControl.getGraphView();// 获取拓扑图组件
       // dm = graphView.getDataModel();// 获取拓扑图中的数据容器

        function init() {

            var center = ol.proj.transform([114.88, 40.82], 'EPSG:4326', 'EPSG:3857');
            var mapDiv = document.getElementById('mapDiv');
            map = new ol.Map({
                target: 'mapDiv',// 地图容器
                controls: ol.control.defaults().extend([
                    graphViewControl,// 自定义拓扑控件
                    //new ol.control.OverviewMap(),// 地图全局视图控件
                    new ol.control.ScaleLine(),// 比例尺控件
                    // new ol.control.ZoomSlider(),// 缩放刻度控件
                    //new ol.control.ZoomToExtent()// 缩放到全局控件
                ]),
                layers: [
                    new ol.layer.Tile({
                        source: new ol.source.XYZ({
                            //瓦片的URL,由于只有冀北地图
                            url: 'http://localhost:8080/maps/{z}/{y}/{x}.png'
                        })
                    })
                ],// 图层
                view: new ol.View({// 地图视图
                    //projection: 'EPSG:3857',// 投影
                    center: center,// 视图的初始中心 中心的坐标系由projection选项指定
                    zoom: 7// 缩放级别 用于计算视图的初始分辨率
                })
            });

            // map.getInteractions().forEach(function(element, index, array) {
            // 	if(element instanceof ol.interaction.DragBox) {
            // 		element.setActive(false);// 禁用 openLayers 的 shift+鼠标左键 方框选中放大功能
            // 	}
            // });
            // var bottomBorderPane = new ht.widget.BorderPane();
            // bottomBorderPane.setCenterView(mapDiv);
            // bottomBorderPane.getView().style.borderTop = '1px solid #eee';
            borderPane = new ht.widget.BorderPane();
            borderPane.setCenterView(mapDiv);
            borderPane.addToDOM();// 将面板组件添加到 body 中
            borderPane.addViewListener(function (e) {
                if (e.kind !== 'validate') return;// 刷新事件


                map.updateSize();// 用第三方插件的时候强制刷新地图
            });
            graphView.getView().addEventListener('mousemove', function (e) {
               // propertyShow(e);// 鼠标移动到节点上时，显示矩形属性栏
            })

            var renderCounter = 0;
            var tempNumber=0.1;
            map.on('postrender', function (e) {
                if (renderCounter === 0) {
                    // 获取拓扑图中的数据容器 map初始化以后增加node   
                    var dataModel = graphView.getDataModel();
                    // 随机颜色数组
                    var colors = ['red', 'green', 'black', 'yellow', 'orange', 'pink', 'blue']
                    for (var i = 0; i < 10; i++) {
                        dataModel.add(createNode((114.98), (40.92+tempNumber), '测试Node', colors[Math.floor(colors.length * Math.random())]));
                        tempNumber=tempNumber+0.1;
                    }
                   
                    renderCounter++;
                }
            });
           // createIcon();
        }
        // 鼠标移动到节点上时，显示矩形属性栏
        function propertyShow(e) {
            var oldHoverNode = graphView._hoverNode;// 获取上一次事件下的图元, _hoverNode 并非 ui 中定义，为自定义变量
            var newNode = graphView.getDataAt(e);// 获取当前事件下的图元

            if (oldHoverNode !== newNode) {
                if ((oldHoverNode instanceof ht.Shape) || (newNode instanceof ht.Shape) || (oldHoverNode instanceof ht.Edge) || (newNode instanceof ht.Edge)) return;// shape和edge类型的节点没有显示属性栏的功能

                if (oldHoverNode || !newNode) {
                    oldHoverNode._popover.tableLayout.getView().style.display = 'none';
                }

                if (newNode && newNode._popover) {// 每个 Node 上都缓存了一个弹出框实例(存在私有变量 _popover 上)
                    var newPopover = newNode._popover.tableLayout;
                    var preferredSize = newPopover.getPreferredSize();// getPreferredSize获取的就是这个 tablelayout 最合适的大小
                    newPopover.setWidth(preferredSize.width);
                    newPopover.setHeight(preferredSize.height);

                    newNode._rect = getScreenRect(graphView, newNode, preferredSize);// 节点的屏幕矩形范围
                    newPopover.getView().style.left = newNode._rect.x + 'px';
                    newPopover.getView().style.top = newNode._rect.y + 'px';

                    if (formPane.getItemById('select').element.isSelected()) {
                        newPopover.getView().style.display = 'block';
                    }
                }
                graphView._hoverNode = newNode;
            }
        }

        // 设置属性栏外部的矩形方框的位置和大小
        function getScreenRect(graphView, node, preferredSize) {
            var tx = graphView.tx(),// 获取水平平移值
                ty = graphView.ty(),// 设置垂直平移值
                pos = node.getPosition(),// 获取节点的位置
                width = node.getWidth(),// 获取节点的宽度
                height = node.getHeight();// 获取节点的高度

            return {// 返回矩形的位置和宽高，显示在节点的正上方的位置
                x: tx + pos.x - preferredSize.width / 2,
                y: ty + pos.y - preferredSize.height - height,
                width: width,
                height: height
            }
        }

        //--------------显示定位标签(openlayer层)------------
        function createIcon() {
            var iconFeatures = [];
            var j = 114.88;   //起点经度
            var w = 40.82;      //起点纬度
            for (var i = 0; i < 5; i++) {//此处循环方式要修改
                j += 0.01;
                w += 0.01;
                var iconFeature = new ol.Feature({
                    geometry: new ol.geom.Point(ol.proj.transform([j, w], 'EPSG:4326',
                        'EPSG:3857')),
                    name: '123',//此处可以随意添加字段以获得你想要的信息
                    starttime: "",   //开始时间
                    j: j,                //经度
                    w: w,                //纬度
                    population: 4000,
                    rainfall: 500
                });
                iconFeatures.push(iconFeature);
            }
            var vectorSource = new ol.source.Vector({
                features: iconFeatures //add an array of features
            });

            var iconStyle = new ol.style.Style({
                image: new ol.style.Icon(({
                    anchor: [0.5, 46],
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'pixels',
                    opacity: 0.75,

                    src: 'custom/images/fengche.png'
                }))
            });
            var vectorLayer = new ol.layer.Vector({
                source: vectorSource,
                style: iconStyle
            });
            map.addLayer(vectorLayer);
        }
        // 创建节点（ht层）
        function createNode(lon, lat, name, color) {
            var node = new ht.Node();
            node.s({
                'shape': 'circle',
                'shape.background': color,
                'label.background': 'rgba(255, 255, 0, 0.5)',
                'select.type': 'circle'
            });
            node.setSize(20, 20);
            node.a('coord', [lon, lat]);// 设置经纬度即可，GraphViewControl自动转成屏幕坐标展示
            return node;
        }
    </script>
</head>

<body onload="init()">
    <div id="mapDiv" style="position: absolute; top: 22px; "></div>
</body>

</html>